package org.apache.struts2.plugin.json.writer;

import java.io.IOException;
import java.io.OutputStream;
import org.apache.struts2.plugin.json.Token;
import org.apache.struts2.plugin.json.model.JSONString;

/**
 * @author VERDOÏA Laurent <verdoialaurent@gmail.com>
 */
public class JSONStringWriter extends AbstractJSONWriter<JSONString> {

    public JSONStringWriter(JSONString content, OutputStream out) {
        super(content, out, Token.STRING_START, Token.STRING_END);
    }

    @Override
    public void writeContent() throws IOException {
        String s = this.content.getData();

        for (int i = 0,  len = s.length(); i < len; i++) {
            out.write(convert(s.charAt(i)));
        }
    }

    public final static byte[] convert(char c) {
        switch (c) {
            case '\"':
                return Token.CHAR_QUOTATION_MARK.getBytes();
            case '\\':
                return Token.CHAR_REVERSE_SOLIDUS.getBytes();
            case '/':
                return Token.CHAR_SOLIDUS.getBytes();
            case '\b':
                return Token.CHAR_BACKSPACE.getBytes();
            case '\f':
                return Token.CHAR_LINE_FEED.getBytes();
            case '\n':
                return Token.CHAR_NEW_LINE.getBytes();
            case '\r':
                return Token.CHAR_CARRIAGE_RETURN.getBytes();
            case '\t':
                return Token.CHAR_HORIZONTAL_TAB.getBytes();
            default:
                if (Character.isISOControl(c)) {
                    byte[] res = new byte[]{'\\', 'u', '0', '0', '0', '0'};
                    byte[] val = Integer.toString((int) c, 16).getBytes();
                    for (int j = 5,  k = val.length - 1; k >= 0; j--, k--) {
                        res[j] = val[k];
                    }
                    return res;
                } else {
                    return Character.toString(c).getBytes();
                }
        }
    }
}
